//
//  RankingList.m
//  WanCaiC8
//
//  Created by tangang on 2018/1/29.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "RankingList.h"
#import "HomeCell.h"
#import "MovementsCell.h"
#import "MovementsContentCell.h"
#import "RankingListCell.h"
#import "RankingModel.h"
#import "LotteryNavTypeView.h"
#import "MasterRankVC.h"
#import "HomePageVM.h"
#import "PlanVC.h"
#import "OpenLotteryRecordVC.h"
#import "JoinQuizDetailVC.h"
#import "InformationVC.h"

#import "RankCell.h"

#import "RankingTotalTopCollectionViewCell.h"

#import "OpenLotteryRecordVC.h"
#import "TGAdvertCollectionReusableView.h"

#import "TGAdvertCollectionViewCell.h"

@interface RankingList ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic ,strong) LotteryNavTypeView *lotteryNavTypeView;
@property (nonatomic ,strong) UICollectionView *collectionView;

//原开奖数据
@property (nonatomic ,strong) NSMutableArray *dataArr;


//开奖记录数据源
//@property (nonatomic ,strong)NSMutableArray *openRecordArr;

@property (nonatomic ,assign)NSInteger   selectLottery;


//全部彩种View
@property (nonatomic ,strong) UIView *totalView;



@property(nonatomic,strong)OpenLotteryRecordVC *openRecordVC;


//开奖首页-彩种分类 不带时间
@property (nonatomic ,strong)NSMutableArray *lotteryList;
//记录 二级彩种分类 带倒计时
@property (nonatomic ,strong)NSMutableArray *secondLotteryList;

/**
是否显示OpenRecordVC
 */
@property (nonatomic ,assign)BOOL isShowOpenRecord;




@property(nonatomic,strong)UIButton *chooseTimeBtn;



@property (nonatomic ,strong) NSMutableArray *arr1;
@property (nonatomic ,strong) NSMutableArray *arr2;
//记录isdisplay为1 的个数
@property (nonatomic ,strong) NSMutableArray *colArr1;
@property (nonatomic ,strong) NSMutableArray *colArr2;


@property (nonatomic ,strong) NSArray *navArr;


@end
@implementation RankingList

#pragma mark - 接收通知
-(void)receiveNotification{
    NSLog(@"___________>接收到通知");
    
    if (self.selectLottery<self.navArr.count) {
        LotteryTypeModel *model = self.navArr[self.selectLottery];
        [self getIndexLotteryListWithParentId:model.Id];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=DEFAULTBGCOLOR;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification) name:@"TGReloadData" object:nil];
    
    self.title = @"开奖直播";

    self.openRecordVC.view.hidden = YES;

    self.selectLottery = -1;
    
    switch (self.type) {
        case RankingListTypeLottery:
            self.title=@"彩票开奖查询";
            [self getNavLotteryTypeList];
            
            [self getAdvertising];
            
            [self getNewIndexLotteryList];
            
            
            break;
        case RankingListTypeRanking:
            self.title=@"排行榜";
            break;
        default:
            break;
    }
    [self.collectionView reloadData];

    [self setRightNavItem];
    
}


-(void)chooseTimeBtnClick:(UIButton *)button{

    [self.openRecordVC onclickScreening];
    
}

-(void)setRightNavItem{
    
    
    UIView *itemView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    
    UIButton *navBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    UIImage *image = [UIImage imageNamed:@"nav_icon"];
    [navBtn setImage:image forState:UIControlStateNormal];
    [navBtn addTarget:self action:@selector(onclickNav) forControlEvents:UIControlEventTouchUpInside];
    [itemView addSubview:navBtn];
    
    self.chooseTimeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.chooseTimeBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [self.chooseTimeBtn addTarget:self action:@selector(chooseTimeBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    [itemView addSubview:self.chooseTimeBtn];
    
    navBtn.frame= CGRectMake(80-image.size.width, 10, image.size.width, image.size.height);

    self.chooseTimeBtn.frame= CGRectMake(0, 10, 40, image.size.height);
    
    self.chooseTimeBtn.hidden = YES;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:itemView];
    

}

-(void)backClick{
    [super backClick];
    
}


#pragma mark --  获取二级彩种分类
-(void)getIndexLotteryListWithParentId:(NSString *)parentId{
    
   
    [SVProgressHUD show];
    
    [[HomePageVM manage] getHomeLotteryList:parentId andSuccess:^(id returnValue) {
  
        [SVProgressHUD dismiss];
        [self.secondLotteryList removeAllObjects];
        [self.secondLotteryList addObjectsFromArray:returnValue];

        [self.collectionView reloadData];
        
    } andFail:^(NSString *errorMessage, NSError *error) {

    }];
    
    
}
#pragma mark --  获取新首页彩种信息列表
- (void)getNewIndexLotteryList{
    
    [[InformationVM manage] getNewIndexLotteryListSuccess:^(id returnValue) {
    
        self.lotteryList= [NSMutableArray arrayWithArray:returnValue];
      
        
        [self.collectionView reloadData];
        
        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}


#pragma mark -- 获取广告

- (void)getAdvertising{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[InformationVM manage] getAdvertWithLocation:@"0" andType:13 Success:^(id returnValue) {
            
            [self insertAdvertisingWithArr:returnValue];
            
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    });
    
}


#pragma mark -- 插入广告
- (void)insertAdvertisingWithArr:(NSArray *)arr{
    self.arr1=[[NSMutableArray alloc] init];
    self.arr2=[[NSMutableArray alloc] init];
    self.colArr1=[[NSMutableArray alloc] init];
    self.colArr2=[[NSMutableArray alloc] init];

    for (AdvertisingModel *model in arr) {
        if (model.Display) {
            if (model.Layer==1) {
                [self.arr1 addObject:model];
                if (model.IsDisplay) {
                    [self.colArr1 addObject:model];
                }
            }else if (model.Layer==2){
                [self.arr2 addObject:model];
                if (model.IsDisplay) {
                    [self.colArr2 addObject:model];
                }
            }
        }
    }
    
    
    if (self.lotteryList.count>2&&self.arr2.count>0) {
        
        [self.lotteryList insertObject:self.arr2 atIndex:2];
    }
    [self.collectionView reloadData];
}
#pragma mark -- 获取彩票导航分类
- (void)getNavLotteryTypeList{
  
        WS(weakSelf);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[HomePageVM manage] getLotteryTypeListWithParentId:@"0" Success:^(id returnValue) {
                
                self.navArr = [NSArray arrayWithArray:returnValue];
                
                if (self.navArr.count>0) {
                    [_lotteryNavTypeView setDataArr:self.navArr];
                }
                
            } Fail:^(NSString *errorMessage, NSError *error) {

            }];
        });

    
}
#pragma mark -- 获取原开奖列表 二级倒计时(可注释)
- (void)getLotteryList:(LotteryTypeModel *)model{
    WS(weakSelf);
    
    [[HomePageVM manage] getHomeLotteryList:model.Id andSuccess:^(id returnValue) {
        [weakSelf.dataArr removeAllObjects];
        [weakSelf.dataArr addObjectsFromArray:returnValue];

    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}



#pragma mark - collectionView代理函数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    if (self.selectLottery == -1) {
        
        return 2;
    }else{
        return 1;
    }

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (self.selectLottery == -1) {
        
        if (section ==0) {
            return 1;
        }
       return self.lotteryList.count;
    
    } else {

        return self.secondLotteryList.count;
       
    }

}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.selectLottery == -1) {
        if (indexPath.section == 0) {
            RankingTotalTopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RankingTotalTopCollectionViewCell" forIndexPath:indexPath];
            cell.isShowDownBtn = YES;
            return cell;
        } else {
            
            
            if ([self.lotteryList[indexPath.row] isKindOfClass:[RankListModel class]]) {
                
                RankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RankCell" forIndexPath:indexPath];
                
                RankListModel *model=self.lotteryList[indexPath.row];
                
                cell.model = model;
                
                return cell;
            }else{
                
                TGAdvertCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGAdvertCollectionViewCell" forIndexPath:indexPath];
                cell.dataArr = self.lotteryList[indexPath.row];
                
                return cell;
                
            }
        
        }
        
    }else {

        
            RankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RankCell" forIndexPath:indexPath];
        
            if (indexPath.row<self.secondLotteryList.count) {
                cell.home_LotteryModel = self.secondLotteryList[indexPath.row];
            }
        
            return cell;
      

    }
       
    

    
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (self.selectLottery == -1) {
        
        if (indexPath.section == 0) {
            return CGSizeMake(SCREEN_WIDTH, 140);
            
        } else {
            
            
            if ([self.lotteryList[indexPath.row] isKindOfClass:[RankListModel class]]) {
                return CGSizeMake(SCREEN_WIDTH/2.0, SCREEN_WIDTH/5.0);

            }else{
                return CGSizeMake(SCREEN_WIDTH,10+40*self.arr2.count-40*ceil(self.colArr2.count/2.0)) ;
            }
        }
        
    }else{
            return CGSizeMake(SCREEN_WIDTH/2.0, SCREEN_WIDTH/5.0);
    }

}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//
//}

//- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//

//}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.selectLottery == -1) {
        
        if (indexPath.section == 0) {
            return;
        }
        
        if ([self.lotteryList[indexPath.row] isKindOfClass:[RankListModel class]]) {
            RankListModel *model=self.lotteryList[indexPath.row];
            
            NSArray *arr = self.navArr.copy;
            
            
            NSInteger temp = 0;
            for (int i= 0; i<arr.count; i++) {
                
                LotteryTypeModel *lotteryTypeModel = arr[i];
                if ([model.BigLType integerValue] == [lotteryTypeModel.lType integerValue]) {
                    temp= i;
                }
            }
            
            self.lotteryNavTypeView.isHomeEnter = YES;
            
            self.lotteryNavTypeView.selectLottery = temp;
            
            
            self.title =[NSString stringWithFormat:@"%@开奖记录",model.LTypeName];
            
            self.chooseTimeBtn.hidden = NO;
            
            self.isShowOpenRecord = YES;
            
            self.openRecordVC.view.hidden = NO;
            
            self.openRecordVC.lType = model.LType;
            
            self.openRecordVC.lotteryType = [[BaseVM manage] getType:[model.LType integerValue]];
        
        }
      
    }else{
        
        
        Home_LotteryModel *model=self.secondLotteryList[indexPath.row];

        self.lotteryNavTypeView.isHomeEnter = YES;
        
//        self.lotteryNavTypeView.selectLottery = temp;
        
        
        self.title =[NSString stringWithFormat:@"%@开奖记录",model.LTypeName];
        self.chooseTimeBtn.hidden = NO;

        self.isShowOpenRecord = YES;
        
        self.openRecordVC.view.hidden = NO;
        
        self.openRecordVC.lType = model.LType;
        
        self.openRecordVC.lotteryType = [[BaseVM manage] getType:[model.LType integerValue]];

        
    }

   
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section ==0 ) {
        return CGSizeZero;
    }else {
        
        if (self.arr1.count) {
            return CGSizeMake(SCREEN_WIDTH, 5+40*(NSInteger)(self.arr1.count-ceil(self.colArr1.count/2.0)));
        }else{
            return CGSizeZero;
        }
        
    }
    
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{

    UICollectionReusableView *reusableView = nil;

    if (kind == UICollectionElementKindSectionHeader)
    {
        
        if (indexPath.section ==1) {
            TGAdvertCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TGAdvertCollectionReusableView" forIndexPath:indexPath];
            if (self.arr1.count) {
                [headerView setAdModelArr:self.arr1 AndRowCount:(NSInteger)(self.arr1.count-ceil(self.colArr1.count/2.0))];
            }
            
            reusableView = headerView;
        }else{
            return reusableView;
        }
    }
    
    return reusableView;

}

#pragma mark - 懒加载
- (LotteryNavTypeView *)lotteryNavTypeView{
    if (!_lotteryNavTypeView) {
        WS(weakSelf);
        _lotteryNavTypeView=[[LotteryNavTypeView alloc] init];
        
        
        _lotteryNavTypeView.chaneBlock = ^(NSInteger row) {
            
            weakSelf.selectLottery=row;
            
            if (row!=-1) {
                LotteryTypeModel *model = weakSelf.navArr[row];
                if (model.SonIdArr.count>1) {
                    
                    weakSelf.title = @"开奖直播";
                    weakSelf.chooseTimeBtn.hidden = YES;

                    weakSelf.isShowOpenRecord = NO;
                    weakSelf.openRecordVC.view.hidden = YES;
                    
                    [weakSelf getIndexLotteryListWithParentId:model.Id];
                    
                    
                } else {
                    
                    weakSelf.title =[NSString stringWithFormat:@"%@开奖记录",model.Name];
                    weakSelf.chooseTimeBtn.hidden = NO;

                    weakSelf.isShowOpenRecord = YES;
                    
                    weakSelf.openRecordVC.view.hidden = NO;
                    
                    weakSelf.openRecordVC.lType = model.SonIdArr.firstObject;
                    weakSelf.openRecordVC.lotteryType = [[BaseVM manage] getType:[model.SonIdArr.firstObject integerValue]];
                }

                
            }else{
                

                weakSelf.title = @"开奖直播";
                
                weakSelf.chooseTimeBtn.hidden = YES;
                weakSelf.isShowOpenRecord = NO;
                weakSelf.openRecordVC.view.hidden = YES;
 
                [weakSelf.collectionView reloadData];
            }
            
        };
        
        [self.view addSubview:_lotteryNavTypeView];
        [_lotteryNavTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(weakSelf.view);
            make.height.mas_equalTo(@40);
        }];
    }
    return _lotteryNavTypeView;
}

- (UICollectionView *)collectionView{
    if (_collectionView==nil) {
        WS(weakSelf);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator=NO;
        
        [_collectionView registerClass:[RankingTotalTopCollectionViewCell class] forCellWithReuseIdentifier:@"RankingTotalTopCollectionViewCell"];
        [_collectionView registerClass:[RankCell class] forCellWithReuseIdentifier:@"RankCell"];
       
        
        [_collectionView registerClass:[TGAdvertCollectionViewCell class] forCellWithReuseIdentifier:@"TGAdvertCollectionViewCell"];
        
        [_collectionView registerClass:[TGAdvertCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TGAdvertCollectionReusableView"];
        
        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(weakSelf.view);
            make.top.equalTo(self.lotteryNavTypeView.mas_bottom);
        }];
        
        //        _collectionView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //            weakSelf.page=1;
        //            [weakSelf.dataArr removeAllObjects];
        //            [weakSelf.tableView reloadData];
        //            [weakSelf getData];
        //        }];
        //        _tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        //            [weakSelf getData];
        //        }];
    }
    return _collectionView;
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
        //        switch (self.type) {
        //            case RankingListTypeLottery:
        //
        //                break;
        //            case RankingListTypeRanking:
        //                [_dataArr addObject:[RankingModel createWithImage:@"ranking_integral" andName:@"积分榜" andNum:5]];
        //                [_dataArr addObject:[RankingModel createWithImage:@"ranking_fans" andName:@"粉丝榜" andNum:4]];
        //                [_dataArr addObject:[RankingModel createWithImage:@"ranking_profit" andName:@"盈利榜" andNum:2]];
        //                [_dataArr addObject:[RankingModel createWithImage:@"ranking_exceptional" andName:@"打赏榜" andNum:1]];
        //                break;
        //            default:
        //                break;
        //        }
    }
    return _dataArr;
}


- (NSMutableArray *)secondLotteryList{
    if (!_secondLotteryList) {
        _secondLotteryList=[[NSMutableArray alloc]init];
    }
    return _secondLotteryList;
}

//
//- (NSMutableArray *)openRecordArr{
//    if (!_openRecordArr) {
//        _openRecordArr=[[NSMutableArray alloc]init];
//    }
//    return _openRecordArr;
//}




//第二个控制器

- (OpenLotteryRecordVC *)openRecordVC{
    if (!_openRecordVC) {
        WS(weakSelf);

        _openRecordVC=[[OpenLotteryRecordVC alloc] init];
        [self.view insertSubview:_openRecordVC.view aboveSubview:self.collectionView];
        [_openRecordVC.view setFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-40)];
        _openRecordVC.view.hidden=YES;
        [self addChildViewController:_openRecordVC];
    }
    return _openRecordVC;
}


- (void)dealloc
{

     NSLog(@"RankList   销毁");
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TGReloadData" object:self];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end


